<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var obj = {
        age: 34,
        name: 'zll',
        like: {
          swim: '游泳',
          sing: '唱歌',
        },
        works: ['上海', '北京'],
        sayHi: function () {
          console.log('sayHi')
        },
      }
      // 浅拷贝，对象里面的引用类型只是拷贝了地址，修改会影响原对象
      // var newObj = Object.assign({},obj)
      // newObj.age = 123
      // newObj.like.swim = '打游戏'
      // newObj.works.push('广州')
      // console.log('newObj',newObj);
      // console.log('obj',obj); //34

      // 深拷贝，对象里面的引用类型拷贝了值，修改不会影响原对象,但是不sayHi方法没有被拷贝走，新对象里面没有sayHi的方法
      // var newObj = JSON.parse(JSON.stringify(obj))
      // newObj.age = 123
      // newObj.like.swim = '打游戏'
      // newObj.works.push('广州')
      // console.log('newObj',newObj);
      // console.log('obj',obj); //34


      function deepCopy(obj) {
        var newObj = obj.constructor === Array ? [] : {}
        if(obj && typeof obj === 'object') {
          for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
              newObj[key] = obj[key] && typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key]
            }
          }
        }
        return newObj
      }

      var newObj = deepCopy(obj)
      newObj.age = 123
      newObj.like.swim = '打游戏'
      newObj.works.push('广州')
      console.log('newObj',newObj);
      console.log('obj',obj); //34
    </script>
  </body>
</html>
